﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.Phone.Controls;
using TweetSharp;
using Hammock;

using System.Diagnostics;

namespace MyMP3
{
    public partial class MainPage : PhoneApplicationPage
    {

        #region Members
        
        // memory stream for twitpic images
        MemoryStream gms;
        // twitter service client
        TwitterService ts = null;
        // twitter service dispatcher
        Dispatcher dispatcher = Deployment.Current.Dispatcher;

        // api service access keys
        // twitpic
        private const string twitpicApiKey = "266bee7387a82df4601f94892588a2df";
        // twitter
        private const string consumerKey = "V7SL4gPkfEI2R02799wwrA";
        private const string consumerSecret = "qxcPpAtCRsEovjKIxhVK46BMb8NQvFvFmr5xwOtKevE";
        private const string accessToken = "76504827-MUu6h4ey0mumUbhdamhUVD3bLUDFrVr39XqyDejpk";
        private const string accessTokenSecret = "VqoWL6WrKhYMKCHOkhTmeX7dAGsBuBNX8zTw1tqh00";

        // data binding presentation
        private TweetPresenter _tweetPresenter;
        public TweetPresenter TweetPresenter
        {
            get
            {
                if (_tweetPresenter == null)
                {
                    _tweetPresenter = new TweetPresenter();
                }
                return _tweetPresenter;
            }
        }

        #endregion

        #region Event Handlers

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            // if we have an image here when we navigated, we will post it to TwitPic
            if ((App.Current as App).ImageBytes != null)
            {
                // post to twitpic
                PostTwitPic();

                // reset photoresult to null
                (App.Current as App).ImageBytes = null;
            }

            base.OnNavigatedTo(e);
        }

        /// <summary>
        /// Callback method for TwitPic
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="userState"></param>
        private void TwitPicCallback(RestRequest request, RestResponse response, object userState)
        {
            // twitpic upload api response documentation: http://dev.twitpic.com/docs/2/upload/

            if (response.StatusCode == HttpStatusCode.OK)
            {
                // todo: build up the tweet using the twitpic response - perhaps a url to the twitpic
                string tweet = "twitpic'd : ";

                XDocument doc = XDocument.Parse(response.Content);
                string url = (from xml in doc.Descendants("image")
                              select xml.Element("url").Value).FirstOrDefault();

                ts.SendTweet(tweet + url, (tweetStatus, tweetResponse) =>
                {
                    if (tweetResponse.StatusCode == HttpStatusCode.OK)
                    {
                        //RefreshTweets();
                    }
                });
            }

            // lets dispose of that memory stream from earlier!
            gms.Dispose();
            gms = null;
        }

        private void ContextMenuDelete_Click(object sender, RoutedEventArgs e)
        {
            // dmm: was testing how to use context menus with the ui toolkit
            // App.ViewModel.Items.Remove((sender as MenuItem).DataContext as ItemViewModel);
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            RefreshTweets();
        }

        private void Capture_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PhotoPage.xaml", UriKind.Relative));
        }

        private void lbTweets_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            Debug.WriteLine("MainPage: lbTweets: SelectedItem: " + lbTweets.SelectedItem.ToString());
        }

        #endregion

        #region Constructors and Initialization

        public MainPage()
        {
            InitializeComponent();

            // lets initialize twitter
            InitializeTwitter();

            // lets refresh my tweets
            RefreshTweets();
        }

        /// <summary>
        /// Initialize our Twitter OAuth service
        /// </summary>
        private void InitializeTwitter()
        {
            ts = new TwitterService(
                new TwitterClientInfo()
                {
                    ConsumerKey = consumerKey,
                    ConsumerSecret = consumerSecret
                }
            );

            ts.AuthenticateWith(
                token: accessToken,
                tokenSecret: accessTokenSecret
            );
        }

        #endregion

        #region Helpers

        /// <summary>
        /// refresh tweets
        /// </summary>
        private void RefreshTweets()
        {
            ts.ListTweetsOnHomeTimeline((statuses, response) =>
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    dispatcher.BeginInvoke(
                        () =>
                        {
                            TweetPresenter.RefreshTweets(statuses);
                        }
                    );
                }
                else
                {
                    TweetPresenter.InsertLocalMessage("Failed loading tweets.");
                }
            });
        }

        /// <summary>
        /// post picture to twitpic
        /// </summary>
        public void PostTwitPic()
        {
            // twitpic upload api documentation: http://dev.twitpic.com/docs/2/upload/

            string file = "MP3_" + DateTime.Now.Ticks.ToString();
            gms = new MemoryStream((App.Current as App).ImageBytes);
            gms.Seek(0, SeekOrigin.Begin);

            RestRequest request = ts.PrepareEchoRequest();
            request.Path = "uploadAndPost.xml";
            request.AddFile("media", file, gms);
            request.AddField("key", twitpicApiKey);
            request.AddField("message", file);

            RestClient client = new RestClient
            {
                Authority = "http://api.twitpic.com/",
                VersionPath = "2",
            };

            client.BeginRequest(request, new RestCallback(TwitPicCallback));
        }

        #endregion

    }
}